import SwiftUI
import UIKit // 导入UIKit便于使用TCP相关功能

// 小车控制视图
struct CarControlView: View {
    @EnvironmentObject var tcpCarService: TCPCarService
    @EnvironmentObject var connectionSettings: ConnectionSettings
    @State private var showVideoFullScreen = false
    @State private var lightOn = false
    @State private var selectedSpeed: SpeedLevel = .medium
    @State private var leftLightOn = false
    @State private var rightLightOn = false
    @State private var doubleLightOn = false
    @State private var doubleFlashOn = false
    @State private var lineFollowOn = false
    
    enum SpeedLevel: String, CaseIterable, Identifiable {
        case low = "低速"
        case medium = "中速"
        case high = "高速"
        var id: String { rawValue }
        var value: UInt8 {
            switch self {
            case .low: return 0x28 // 40
            case .medium: return 0x46 // 70
            case .high: return 0x64 // 100
            }
        }
    }
    
    // 方向按钮定义
    let directionButtons: [(label: String, icon: String, value: UInt8)] = [
        ("前进", "arrow.up", 1),
        ("后退", "arrow.down", 2),
        ("左平移", "arrow.left", 3),
        ("右平移", "arrow.right", 4),
        ("左旋", "arrow.uturn.left", 5),
        ("右旋", "arrow.uturn.right", 6),
        ("停止", "stop.fill", 0),
        ("急停", "exclamationmark.triangle.fill", 7)
    ]
    
    // 灯光秀动作序列（直接定义完整的运动命令）
       let lightShowSequence: [(direction: UInt8, duration: Double)] = [
           (1, 1.0),  // 前进1秒
           (0, 0.5),  // 暂停0.5秒
           (2, 1.0),  // 后退1秒
           (0, 0.5),  // 暂停0.5秒
           (3, 0.8),  // 左平移0.8秒
           (0, 0.3),  // 暂停0.3秒
           (4, 0.8),  // 右平移0.8秒
           (0, 0.3),  // 暂停0.3秒
           (5, 1.5),  // 左旋1.5秒
           (0, 0.3),  // 暂停0.3秒
           (6, 1.5),  // 右旋1.5秒
           (0, 1.0)   // 最终停止1秒
       ]
    
    var body: some View {
        ScrollView {
            VStack(spacing: 18) {
                // 视频窗口
                ZStack(alignment: .topTrailing) {
                    GeometryReader { geometry in
                        VideoStreamView()
                            .frame(width: geometry.size.width - 32, height: min(220, (geometry.size.width - 32) * 9 / 16))
                            .clipped()
                            .cornerRadius(12)
                            .padding(.horizontal, 16)
                            .onTapGesture {
                                showVideoFullScreen = true
                            }
                    }
                    .frame(height: 220)
                    // 只保留全屏按钮
                    Button(action: {
                        showVideoFullScreen = true
                    }) {
                        Image(systemName: "arrow.up.left.and.arrow.down.right")
                            .font(.system(size: 18))
                            .padding(8)
                            .background(Color.black.opacity(0.5))
                            .foregroundColor(.white)
                            .clipShape(Circle())
                    }
                    .padding(8)
                }
                .padding(.bottom, 8)
                // 相机控制按钮，增加鸣笛
                HStack(spacing: 30) {
                    CameraControlView(
                        onTakePhoto: { sendTakePhotoCommand() },
                        onStartVideo: { sendStartVideoCommand() },
                        onStopVideo: { sendStopVideoCommand() }
                    )
                    Button(action: {
                        sendHornCommand()
                    }) {
                        VStack {
                            Image(systemName: "speaker.wave.3.fill")
                                .font(.system(size: 30))
                                .foregroundColor(.yellow)
                            Text("鸣笛")
                                .font(.caption)
                        }
                    }
                }
                .padding(.bottom, 12)
                // 方向控制区
                VStack(spacing: 12) {
                    Text("方向控制").font(.headline)
                    // 九宫格布局
                    VStack(spacing: 12) {
                        // 第一行：急停、前进、右旋
                        HStack(spacing: 24) {
                            directionButtonView(type: 7) // 急停左上
                            directionButtonView(type: 1) // 前进中上
                            Spacer()
                                    .frame(width: 60)
                        }
                        // 第二行：左旋、停止、右转
                        HStack(spacing: 24) {
                            directionButtonView(type: 3) // 左平移左中
                            directionButtonView(type: 0) // 停止正中
                            directionButtonView(type: 4) // 右平移右中
                        }
                        // 第三行：左转、后退、右下空
                        HStack(spacing: 24) {
                            directionButtonView(type: 5) // 左转左下
                            directionButtonView(type: 2) // 后退中下
                            directionButtonView(type: 6) // 右旋右下
                        }
                    }
                }
                .padding(.horizontal)
                // 三档速度选择
                VStack(alignment: .leading, spacing: 8) {
                    Text("速度选择").font(.headline)
                    Picker("速度", selection: $selectedSpeed) {
                        ForEach(SpeedLevel.allCases) { level in
                            Text(level.rawValue).tag(level)
                        }
                    }
                    .pickerStyle(SegmentedPickerStyle())
                    .onChange(of: selectedSpeed) { value in
                        sendSpeedCommand(value)
                    }
                }
                .padding(.horizontal)
                // 灯光控制
                VStack(alignment: .leading, spacing: 8) {
                    Text("灯光控制").font(.headline)
                    HStack(spacing: 16) {
                        Toggle("左灯", isOn: $leftLightOn)
                            .font(.caption)
                            .onChange(of: leftLightOn) { v in sendLightCommand(type: 0x65, on: v) }
                        Toggle("右灯", isOn: $rightLightOn)
                            .font(.caption)
                            .onChange(of: rightLightOn) { v in sendLightCommand(type: 0x66, on: v) }
                        Toggle("双灯", isOn: $doubleLightOn)
                            .font(.caption)
                            .onChange(of: doubleLightOn) { v in sendLightCommand(type: 0x67, on: v) }
                        Toggle("双闪", isOn: $doubleFlashOn)
                            .font(.caption)
                            .onChange(of: doubleFlashOn) { v in sendLightCommand(type: 0x68, on: v) }
                    }
                    .toggleStyle(SwitchToggleStyle(tint: .yellow))
                }
                .padding(.horizontal)
                
                // 巡线开关
                VStack(alignment: .leading, spacing: 8) {
                    Text("巡线模式").font(.headline)
                    Toggle(lineFollowOn ? "巡线已开启" : "巡线已关闭", isOn: $lineFollowOn)
                        .onChange(of: lineFollowOn) { v in
                            sendLineFollowCommand(on: v)
                        }
                        .toggleStyle(SwitchToggleStyle(tint: .green))
                }
                .padding(.horizontal)
//                // 速度控制
//                SpeedControlView(
//                    onSpeedUp: { tcpCarService.increaseSpeed() },
//                    onSpeedDown: { tcpCarService.decreaseSpeed() }
//                )
            }
            .padding()
            .padding(.bottom, 30) // 添加底部额外的间距，避免被Tab栏遮挡
        }
        .fullScreenCover(isPresented: $showVideoFullScreen) {
            // 全屏视频显示
            ZStack {
                Color.black.edgesIgnoringSafeArea(.all)
                VStack {
                    VideoStreamView()
                        .edgesIgnoringSafeArea(.all)
                    // 关闭按钮
                    Button(action: {
                        showVideoFullScreen = false
                    }) {
                        Image(systemName: "xmark")
                            .font(.title)
                            .foregroundColor(.white)
                            .padding()
                            .background(Color.black.opacity(0.5))
                            .clipShape(Circle())
                    }
                    .padding(.bottom, 20)
                }
            }
        }
    }
       
    
    // 自定义高亮按钮样式
    struct HighlightButtonStyle: ButtonStyle {
        func makeBody(configuration: Configuration) -> some View {
            configuration.label
                .scaleEffect(configuration.isPressed ? 0.92 : 1.0)
                .background(configuration.isPressed ? Color.blue.opacity(0.18) : Color.clear)
                .overlay(
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(configuration.isPressed ? Color.blue : Color.clear, lineWidth: 2)
                )
                .animation(.easeInOut(duration: 0.12), value: configuration.isPressed)
        }
    }
    
    // 单个方向按钮视图
    @ViewBuilder
    func directionButtonView(type: UInt8) -> some View {
        if let btn = directionButtons.first(where: { $0.value == type }) {
            Button(action: {
                sendDirectionCommand(btn.value)
            }) {
                VStack {
                    Image(systemName: btn.icon)
                        .font(.title)
                        .foregroundColor(type == 7 ? .red : .blue)
                    Text(btn.label).font(.caption)
                }
                .frame(width: 60, height: 60)
                .background(Color(.systemGray6))
                .cornerRadius(10)
                .contentShape(Rectangle())
            }
            .buttonStyle(HighlightButtonStyle()) // 应用自定义高亮样式
        } else {
            Spacer()
        }
    }
    
    // 发送方向控制协议
    func sendDirectionCommand(_ direction: UInt8) {
        print("[CarControlView] 发送方向命令: type=\(direction)")
        // 只需1个字节数据（方向值）
        let cmd = CarProtocolBuilder.buildCommand(
            carType: 0x01,
            functionCode: 0x15,
            data: [direction] // 关键修改：只传方向值
        )
        print("[CarControlView] 方向协议内容: \(String(data: cmd, encoding: .utf8) ?? "<编码失败>")")
        tcpCarService.sendData(cmd) { success in
            print("[CarControlView] 方向命令发送\(success ? "成功" : "失败") type=\(direction)")
        }
    }
    // 发送速度协议
    func sendSpeedCommand(_ level: SpeedLevel) {
        print("[CarControlView] 发送速度命令: level=\(level.rawValue)")
        let v = level.value
        let data: [UInt8] = [v, v] // 6字节数据，X/Y速度和Z速度
        let cmd = CarProtocolBuilder.buildCommand(carType: 0x01, functionCode: 0x16, data: data)
        print("[CarControlView] 速度协议内容: \(String(data: cmd, encoding: .utf8) ?? "<编码失败>")")
        tcpCarService.sendData(cmd) { success in
            print("[CarControlView] 速度命令发送\(success ? "成功" : "失败") level=\(level.rawValue)")
        }
    }
    
    
    // 灯光控制函数更新
    func sendLightCommand(type: UInt8, on: Bool) {
        print("[CarControlView] 发送灯光命令: type=\(type), on=\(on)")
        
        // 根据协议构建命令 - 使用1/0表示开关状态
        let lightData: [UInt8] = [on ? 1 : 0]
        let cmd = CarProtocolBuilder.buildCommand(
            carType: 0x01,
            functionCode: type,
            data: lightData,
//            fixedLength: 0x02  // 关键修改：固定长度为0x02
        )
        
        print("[CarControlView] 灯光协议内容: \(String(data: cmd, encoding: .utf8) ?? "<编码失败>")")
        tcpCarService.sendData(cmd) { success in
            print("[CarControlView] 灯光命令发送\(success ? "成功" : "失败") type=\(type), on=\(on)")
        }
    }

    func sendLineFollowCommand(on: Bool) {
        print("[CarControlView] 发送巡线命令: on=\(on)")
        
        // 根据协议构建命令 (无数据字段)
        let functionCode: UInt8 = on ? 0x63 : 0x64
        let cmd = CarProtocolBuilder.buildCommand(
            carType: 0x01,
            functionCode: functionCode,
            data: []
        )
        
        print("[CarControlView] 巡线协议内容: \(String(data: cmd, encoding: .utf8) ?? "<编码失败>")")
        tcpCarService.sendData(cmd) { success in
            print("[CarControlView] 巡线命令发送\(success ? "成功" : "失败") on=\(on)")
        }
    }

    // 鸣笛指令
    func sendHornCommand() {
        print("[CarControlView] 发送鸣笛指令")
        let hornStatus: UInt8 = 0x01 // 始终为开启
        let delay: UInt8 = 0x01      // 持续时间，可根据需要调整
        let data: [UInt8] = [hornStatus, delay]
        let cmd = CarProtocolBuilder.buildCommand(
            carType: 0x01,
            functionCode: 0x13,
            data: data,
            fixedLength: 0x06
        )
        print("[CarControlView] 鸣笛协议内容: \(String(data: cmd, encoding: .utf8) ?? "<编码失败>")")
        tcpCarService.sendData(cmd) { success in
            print("[CarControlView] 鸣笛命令发送\(success ? "成功" : "失败")")
        }
    }

    // 拍照指令
    func sendTakePhotoCommand() {
        print("[CarControlView] 发送拍照指令")
        let cmd = CarProtocolBuilder.buildCommand(
            carType: 0x01,
            functionCode: 0x60, // 拍照功能位
            data: [],
            fixedLength: 0x02
        )
        print("[CarControlView] 拍照协议内容: \(String(data: cmd, encoding: .utf8) ?? "<编码失败>")")
        tcpCarService.sendData(cmd) { success in
//            print("[CarControlView] 拍照命令发送\(success ? \"成功\" : \"失败\")")
        }
    }
    // 开始录像指令
    func sendStartVideoCommand() {
        print("[CarControlView] 发送开始录像指令")
        let cmd = CarProtocolBuilder.buildCommand(
            carType: 0x01,
            functionCode: 0x61, // 开始录像功能位
            data: [],
            fixedLength: 0x02
        )
        print("[CarControlView] 开始录像协议内容: \(String(data: cmd, encoding: .utf8) ?? "<编码失败>")")
        tcpCarService.sendData(cmd) { success in
//            print("[CarControlView] 开始录像命令发送\(success ? \"成功\" : \"失败\")")
        }
    }
    // 结束录像指令
    func sendStopVideoCommand() {
        print("[CarControlView] 发送结束录像指令")
        let cmd = CarProtocolBuilder.buildCommand(
            carType: 0x01,
            functionCode: 0x62, // 结束录像功能位
            data: [],
            fixedLength: 0x02
        )
        print("[CarControlView] 结束录像协议内容: \(String(data: cmd, encoding: .utf8) ?? "<编码失败>")")
        tcpCarService.sendData(cmd) { success in
//            print("[CarControlView] 结束录像命令发送\(success ? \"成功\" : \"失败\")")
        }
    }
}

// 预览
struct CarControlView_Previews: PreviewProvider {
    static var previews: some View {
        CarControlView()
            .environmentObject(TCPCarService())
            .environmentObject(ConnectionSettings())
    }
} 
